package com.fiberhome.nas.feature.main.view

import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Sort
import androidx.compose.material.icons.filled.AddCard
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.MoreHoriz
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.fiberhome.nas.core.designsystem.component.SpaceAroundRow
import com.fiberhome.nas.core.designsystem.component.SpaceBetweenRow
import com.fiberhome.nas.core.designsystem.theme.SpaceHorizontalLarge
import com.fiberhome.nas.core.designsystem.theme.SpaceHorizontalSmall
import com.fiberhome.nas.core.designsystem.theme.SpacePaddingLarge
import com.fiberhome.nas.core.designsystem.theme.SpaceVerticalSmall
import com.fiberhome.nas.core.designsystem.theme.TextSecondaryLight
import com.fiberhome.nas.core.model.entity.PhotoInfo
import com.fiberhome.nas.core.ui.component.image.CheckImage
import com.fiberhome.nas.core.ui.component.image.DevicePhotoImage
import com.fiberhome.nas.core.ui.component.image.TextImage
import com.fiberhome.nas.core.util.time.formatISOToDate
import com.fiberhome.nas.feature.common.ext.photoGridDragHandler
import com.fiberhome.nas.feature.main.viewmodel.PhotoViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterialApi::class)
@SuppressLint("StateFlowValueCalledInComposition")
@Composable
fun PhotoRoute(
    gridState: LazyGridState,
    viewModel: PhotoViewModel = hiltViewModel(),
) {
    val scope = rememberCoroutineScope()
    val photos by viewModel.photos.collectAsState()
    val editMode by viewModel.editMode.collectAsState()
    val selectedItems by viewModel.selectedItems.collectAsState()
    var refreshing by remember { mutableStateOf(false) }
    val refreshState = rememberPullRefreshState(
        refreshing = refreshing,
        onRefresh = {
            scope.launch {
                refreshing = true
                viewModel.refreshData()
                refreshing = false
            }
        })

    Box(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(refreshState)
    ) {
        PhotoScreen(
            gridState = gridState,
            photos = photos,
            editMode = editMode,
            selectedItems = selectedItems,
            enterEditMode = viewModel::enterEditMode,
            onToggleSelectAll = viewModel::toggleSelectAll,
            onToggleItemSelection = viewModel::toggleItemSelection,
            onToggleItemsSelection = viewModel::toggleItemsSelection,
            getPhotoThumbUrl = viewModel::getPhotoThumbUrl
        )

        PullRefreshIndicator(
            refreshing = refreshing,
            state = refreshState,
            modifier = Modifier.align(Alignment.TopCenter)
        )
    }


}

@Composable
fun PhotoScreen(
    gridState: LazyGridState,
    photos: List<PhotoInfo>,
    editMode: Boolean = false,
    selectedItems: Set<String> = emptySet(),
    enterEditMode: () -> Unit = {},
    onToggleSelectAll: (Boolean) -> Unit,
    onToggleItemSelection: (String) -> Unit,
    onToggleItemsSelection: (List<String>, Boolean) -> Unit,
    getPhotoThumbUrl: (String) -> String,
) {
    // 按日期分组
    val photosByDate = photos
        .sortedByDescending { it.fileCreatedAt }
        .groupBy { it.fileCreatedAt.formatISOToDate() }

    val autoScrollSpeed = remember { mutableStateOf(0f) }
    val selectedIds: MutableState<Set<String>> = rememberSaveable { mutableStateOf(emptySet()) }

    //滑动监听
    LaunchedEffect(autoScrollSpeed.value) {
        if (autoScrollSpeed.value != 0f) {
            while (isActive) {
                gridState.scrollBy(autoScrollSpeed.value)
                delay(10)
            }
        }
    }

    // 添加监听 selectedItems 变化并更新 selectedIds
    LaunchedEffect(selectedItems) {
        selectedIds.value = selectedItems.toSet()
    }

    Box {
        LazyVerticalGrid(
            state = gridState,
            columns = GridCells.Fixed(4),
            modifier = Modifier
                .fillMaxSize()
                .then(
                    if (editMode) {
                        Modifier.photoGridDragHandler(  //手势滑动选中
                            lazyGridState = gridState,
                            haptics = LocalHapticFeedback.current,
                            selectedIds = selectedIds,
                            onSelectionChanged = onToggleItemsSelection,
                            autoScrollSpeed = autoScrollSpeed,
                            autoScrollThreshold = with(LocalDensity.current) { 40.dp.toPx() }
                        )
                    } else Modifier
                ),
            horizontalArrangement = Arrangement.spacedBy(SpaceHorizontalSmall),
            verticalArrangement = Arrangement.spacedBy(SpaceVerticalSmall),
            contentPadding = PaddingValues(
                SpacePaddingLarge,
                SpacePaddingLarge,
                SpacePaddingLarge,
                100.dp
            ),
        ) {
            //吸顶
            stickyHeader {
                SortContent()
            }
            //内容
            photosByDate.forEach { (date, photos) ->
                // 日期标题
                item(span = { GridItemSpan(4) }) {
                    SpaceBetweenRow {
                        Text(
                            text = date,
                            fontSize = 14.sp,
                            color = TextSecondaryLight,
                            modifier = Modifier.padding(vertical = 8.dp)
                        )
                        AnimatedVisibility(
                            visible = editMode,
                            enter = fadeIn(),
                            exit = fadeOut(),
                        ) {
                            val photoIds = photos.map { it.id }
                            val selected = selectedItems.containsAll(photoIds)
                            CheckImage(
                                modifier = Modifier
                                    .clickable { onToggleItemsSelection(photoIds, !selected) },
                                selected = selected,
                            )
                        }
                    }
                }
                // 照片网格项
                items(photos, key = { it.id }) { photo ->
                    val selected = selectedItems.contains(photo.id)
                    DevicePhotoImage(
                        photo = photo,
                        photoUrl = getPhotoThumbUrl(photo.id),
                        editMode = editMode,
                        selected = selected,
                        modifier = Modifier
                            .combinedClickable(
                                onClick = {
                                    if (editMode) {
                                        onToggleItemSelection(photo.id)
                                    } else {
                                        // 点击图片，进入详情页
                                    }
                                },
                                onLongClick = {
                                    enterEditMode()
                                }
                            )
                    )
                }
            }
        }
        if (editMode) {
            // 编辑模式底部操作栏
            ActionBottomBar(
                modifier = Modifier
                    .padding(vertical = 40.dp, horizontal = SpaceHorizontalLarge)
                    .align(Alignment.BottomCenter)
            )
        }
    }
}

/**
 * 编辑模式底部操作栏
 */
@Composable
fun ActionBottomBar(modifier: Modifier = Modifier) {
    Card(
        modifier = modifier,
        elevation = CardDefaults.cardElevation(2.dp),
    ) {
        SpaceAroundRow {
            // 下载
            TextImage(
                icon = Icons.Filled.Download,
                text = "下载",
                onClick = { /* 下载操作 */ }
            )

            // 收藏
            TextImage(
                icon = Icons.Filled.FavoriteBorder,
                text = "收藏",
                onClick = { /* 收藏操作 */ }
            )

            // 添加到相册
            TextImage(
                icon = Icons.Filled.AddCard,
                text = "添加到相册",
                onClick = { /* 添加到相册操作 */ }
            )

            // 删除
            TextImage(
                icon = Icons.Filled.Delete,
                text = "删除",
                onClick = { /* 删除操作 */ }
            )

            // 更多
            TextImage(
                icon = Icons.Filled.MoreHoriz,
                text = "更多",
                onClick = { /* 更多操作 */ }
            )
        }
    }
}

/**
 * 照片排序内容
 */
@Composable
private fun SortContent() {
    SpaceBetweenRow(Modifier.padding(horizontal = SpaceHorizontalSmall)) {
        // 第一个Text：居中显示
        Text(
            text = "照片0 | 视频2",
            textAlign = TextAlign.Center,
            modifier = Modifier.weight(1f), // 占据剩余空间
        )
        // 第二个Image：右对齐
        Image(
            imageVector = Icons.AutoMirrored.Filled.Sort,
            contentDescription = "排序",
            modifier = Modifier
                .size(24.dp)
                .clickable { /* 排序 */ }
        )
    }
}

